<template>
  <div class="wrapper">
    <div class="form-container">
      <el-form :model="form" ref="refForm" :rules="ruleForm" label-position="right" label-width="60">
        <el-form-item label="姓名" prop="userInfo.fullName">
          <el-input v-model="form.userInfo.fullName" placeholder="请输入姓名"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="userInfo.phonenumber">
          <el-input v-model="form.userInfo.phonenumber" placeholder="请输入手机号"></el-input>
        </el-form-item>
        <el-form-item label="验证码" prop="userInfo.smsCode">
          <el-input v-model="form.userInfo.smsCode" placeholder="请输入验证码"></el-input>
          <span class="sms-code"
            ><el-button type="text" :disabled="codeTime > 0" @click="handleGetSmsCode">{{
              codeTime > 0 ? `${codeTime}秒后重新获取` : "获取验证码"
            }}</el-button></span
          >
        </el-form-item>

        <el-form-item label="主岗" prop="majorPost.roleId">
          <el-radio-group @change="changeMajorPost" v-model="form.majorPost.roleId" size="small">
            <el-radio-button v-for="item in ps" :key="item.roleId" :label="item.roleName" :value="item.roleId" />
          </el-radio-group>
        </el-form-item>
        <el-form-item label="辅岗" prop="auxiliaryPost">
          <el-checkbox-group v-model="form.auxiliaryPost as string[]" @change="changeAxiliaryPost" size="small">
            <el-checkbox-button size="small" v-for="item in ps" :key="item.roleId" :label="item.roleName" :value="item.roleId" />
          </el-checkbox-group>
        </el-form-item>
      </el-form>
      <div class="table-container">
        <div class="title">
          攸诺运管<span style="margin-left: 5px; font-size: 12px; font-weight: 700; color: #999999">(WEB)</span>
        </div>
        <div class="table-content">
          <el-table
            border
            :cell-style="{ textAlign: 'center', fontSize: '13px' }"
            :header-cell-style="{
              textAlign: 'center',
              fontWeight: '100',
              fontSize: '13px',
              color: 'white',
              backgroundColor: '#009688'
            }"
            style="width: 100%"
            :data="permissionData"
          >
            <el-table-column fixed label="一级权限" prop="firstName"> </el-table-column>
            <el-table-column label="二级权限" prop="secondName"> </el-table-column>
          </el-table>
        </div>
      </div>
      <div class="btn-container">
        <el-button type="primary" @click="handleGetSmsCode"> 取消 </el-button>
        <el-button type="primary" @click="handleSubmit(refForm as FormInstance)">{{ btnStatus ? "保存" : "修改" }}</el-button>
      </div>
    </div>
  </div>
</template>
<script lang="tsx" setup name="proStaffAdd">
import { onMounted, ref } from "vue";
import { Post, Staff } from "@/api/interface/province/organizationManage";
import { addStaffAPI, getPostListAPI, staffDetailAPI, updateStaffAPI } from "@/api/modules/province/organizMangeAPI";
import { ElMessage, FormInstance, FormRules } from "element-plus";
import { getSmsCodeAPI } from "@/api/modules/dictAPI";
import { useRoute, useRouter } from "vue-router";
const route = useRoute();
const router = useRouter();
const btnStatus = ref<boolean>(true);
let form = ref<Staff.Add>({
  auxiliaryPost: [],
  majorPost: {
    roleId: ""
  },
  userInfo: {
    province: JSON.parse(localStorage.getItem("userInfo") as string).province,
    city: JSON.parse(localStorage.getItem("userInfo") as string).city
  }
});
const permissionData = ref<
  {
    firstName: string;
    secondName: string[];
  }[]
>([
  {
    firstName: "",
    secondName: []
  }
]);
// watch(form, (newValue, oldValue) => {
//  console.log(newValue, oldValue);
// });
// const permissionData = computed(() => {});
const refForm = ref<FormInstance>();
const ruleForm = ref<FormRules>({
  "userInfo.fullName": [
    { required: true, message: "请输入姓名", trigger: "blur" },
    { min: 2, max: 10, message: "长度在 2 到 10 个字符", trigger: "blur" }
  ],
  "userInfo.phonenumber": [
    { required: true, message: "请输入手机号", trigger: "blur" },
    { pattern: /^1[34578]\d{9}$/, message: "手机号格式不正确", trigger: "blur" }
  ],
  "userInfo.smsCode": [
    { required: true, message: "请输入验证码", trigger: "blur" },
    { min: 4, max: 6, message: "长度为 6", trigger: "blur" }
  ],
  "majorPost.roleId": [{ required: true, message: "请选择主岗", trigger: "change" }],
  auxiliaryPost: [{ required: true, message: "请选择辅岗", trigger: "change" }]
});
const changeMajorPost = () => {
  permissionData.value[0].firstName = ps.value.filter(item => item.roleId == form.value.majorPost.roleId)[0].roleName as string;
};
const changeAxiliaryPost = () => {
  permissionData.value[0].secondName = form.value.auxiliaryPost.map(
    item => ps.value.filter(i => i.roleId == item)[0].roleName as string
  );
};
let codeTime = ref<number>(0);
const handleGetSmsCode = (): void => {
  if (form.value.userInfo.phonenumber) {
    getSmsCode();
    codeTime.value = 60;
    let timer = setInterval(() => {
      codeTime.value--;
      if (codeTime.value <= 0) {
        clearInterval(timer);
      }
    }, 1000);
  } else {
    ElMessage.error("请输入手机号");
  }
};
const handleSubmit = (formEl: FormInstance) => {
  formEl.validate((valid: boolean) => {
    if (valid) {
      const tm = ref<Staff.AuxiliaryPost[]>([]);
      form.value.auxiliaryPost.forEach(item => {
        tm.value.push({
          roleId: item
        });
      });
      form.value.auxiliaryPost = tm.value;
      btnStatus.value ? addStaff() : updateStaff();
    } else {
      ElMessage.error("请检查输入项");
    }
  });
};
let ps = ref<Post.PostList[]>([]);
const getPost = async () => {
  const { code, rows, total } = await getPostListAPI({
    pageNum: 1,
    pageSize: 100,
    province: JSON.parse(localStorage.getItem("userInfo") as string).province,
    roleName: "",
    companyType: "2"
  });
  if (code == "200" && rows && total) {
    ps.value = rows;
  }
};
const addStaff = async () => {
  const { code, msg } = await addStaffAPI(form.value as Staff.Add);
  if (code == "200") {
    ElMessage.success("添加成功");
    router.push({ path: "/cityLevel/cityOrganization/cityStaff/index" });
  } else {
    ElMessage.error(msg);
  }
};
const updateStaff = async () => {
  form.value.userInfo.userId = Number(route.query.id);
  delete form.value.userInfo.province;
  delete form.value.userInfo.city;
  // delete form.value.userInfo.smsCode;
  const { code, msg } = await updateStaffAPI(form.value as Staff.Add);
  if (code == "200") {
    ElMessage.success("修改成功");
    router.push({ path: "/cityLevel/cityOrganization/cityStaff/index" });
  } else {
    ElMessage.error(msg);
  }
};
const staffDetail = async () => {
  const { code, data, msg } = await staffDetailAPI(Number(route.query.id));
  if (code == "200" && data) {
    console.log("执行了查询详情", data);
    form.value.majorPost.roleId = data.majorPost.roleId;
    form.value.userInfo.fullName = data.userInfo.fullName;
    form.value.userInfo.phonenumber = data.userInfo.phonenumber;
    form.value.userInfo.smsCode = "";
    form.value.auxiliaryPost = [];
    data.auxiliaryPost.forEach(item => {
      console.log(item.roleId);
      form.value.auxiliaryPost.push(item.roleId);
    });
    console.log(form.value.auxiliaryPost);
    changeMajorPost();
    changeAxiliaryPost();
  } else {
    ElMessage.error(msg);
  }
};
const getSmsCode = async () => {
  const { code, msg } = await getSmsCodeAPI({ phone: form.value.userInfo.phonenumber as string });
  if (code == "200") {
    ElMessage.success("验证码发送成功");
  } else {
    ElMessage.error(msg);
  }
};
onMounted(() => {
  getPost();
  if (route.query.id != undefined) {
    staffDetail();
    btnStatus.value = false;
  }
});
</script>
<style lang="scss" scoped>
.wrapper {
  padding: 15px;
  font-size: 13px !important;
  background-color: white;
  .form-container {
    width: 60%;
    margin: 0 auto;
    .el-form-item {
      margin-right: 15px;
    }
    .sms-code {
      //   float: right;
      position: absolute;
      right: 5px;
      display: inline-block;
    }
  }
  .title {
    margin: 15px 0;

    // margin-left: 22px;
    font-size: 12px;
    font-weight: 700;
  }
  .radio-container {
    // margin-left: 24px;
    vertical-align: bottom;
    span {
      display: inline-block;
      height: 10px;
      margin-right: 15px;
      margin-left: 24px;
      line-height: 15px;
      vertical-align: middle;
    }
  }
  .table-container {
    margin-left: 20px;
    .table-content {
      display: inline-block;
      width: 100%;
      margin-left: 20px;
    }
  }
}
.btn-container {
  margin-top: 15px;
  text-align: center;
  button {
    margin-right: 15px;
  }
}
::v-deep .el-form-item__label {
  font-size: 12px;
  font-weight: 700;
  color: #999999;
}
::v-deep .el-button > span {
  font-size: 13px;
}
::v-deep .el-input__inner {
  font-size: 13px;
}
::v-deep .el-radio-button__inner {
  font-size: 12px;
}
</style>
